package com.jinbo.footmessage.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.view.View;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;

import java.util.HashMap;

/**百度地图选择地址 使用工具类
 * Created by jinbo on 2015/8/11.
 */
public class BaiduMapUtils {
    private Context context;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private GeoCoder coder;
    private PoiSearch mPoiSearch;
    private SuggestionSearch mSuggestionSearch;
    private InfoWindow mInfoWindow;

    /**
     * 构造函数
     *
     * @param mMapView 地图组件
     */
    public BaiduMapUtils(View mMapView, Context context) {
        this.context = context;
        this.mMapView =(MapView)mMapView;
        mBaiduMap =this.mMapView.getMap();

    }

    public BaiduMapUtils() {

    }
    /**
     * 放大地图级别到15
     */
    public void updateMapStatus(int n) {
        MapStatus mMapStatus = new MapStatus.Builder()
                .zoom(n)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        mBaiduMap.setMapStatus(mMapStatusUpdate);
    }

    /**
     * 动画移动地图到指定位置
     *
     *
     */
    public void moveMap(double latitude, double Longitude) {
        LatLng cenpt = new LatLng(latitude, Longitude);
        MapStatus mMapStatus = new MapStatus.Builder().target(cenpt)
                .build();
        // 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
                .newMapStatus(mMapStatus);
        mBaiduMap.setMapStatus(mMapStatusUpdate);

    }

    /**
     * 动画移动地图到指定位置
     *
     *
     */
    public void animateMap(double latitude, double Longitude) {
        LatLng cenpt = new LatLng(latitude, Longitude);
        MapStatus mMapStatus = new MapStatus.Builder().target(cenpt)
                .build();
        // 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
                .newMapStatus(mMapStatus);
        mBaiduMap.animateMapStatus(mMapStatusUpdate);

    }


    /**
     * 定位参数配置
     */
    public void setLocaion() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocationClient = new LocationClient(context);
        //mMyLocationListener = new MyLocationListener();
        //  mLocationClient.registerLocationListener(mMyLocationListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(com.baidu.location.LocationClientOption.LocationMode.Hight_Accuracy);// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");// ;.setCoorType(“bd09ll”);//可选，默认gcj02，设置返回的定位结果坐标系
        // int span=1000;
        //option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);// 可选，默认false,设置是否使用gps
        //option.setLocationNotify(true);// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);// 可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);// 可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    /**
     * 开始定位
     */
    public void startLocation() {
        mLocationClient.start();
    }

    /**
     * 请求定位
     */
    public void requestLocation() {
        mLocationClient.requestLocation();
    }

    /**
     * 关闭定位层
     */
    public void stopLocation() {
        if(mLocationClient!=null)
        {
            mLocationClient.stop();
        }
       // mBaiduMap.setMyLocationEnabled(false);
    }
    /**
     * 关闭定位层
     */
    public void stopLocationEnabled() {
        mBaiduMap.setMyLocationEnabled(false);
    }

    /**
     * 关闭地图
     */
    public void destoryMapview() {
        mMapView.onDestroy();
        mMapView = null;
    }

    /**
     * 暂停地图
     */
    public void onPauseMapview() {
        mMapView.onPause();
    }

    /**
     * 运行地图
     */
    public void onResumeMapview() {
        mMapView.onResume();
    }

    public void instanceCoder() {
        coder = GeoCoder.newInstance();
    }

    /**
     * 反编码：从经纬度得到地址信息
     *
     *
     */
    public void reverseGeoCode(double latitude, double Longitude) {
        LatLng code = new LatLng(latitude, Longitude);
        ReverseGeoCodeOption reverseCode = new ReverseGeoCodeOption();
        ReverseGeoCodeOption result = reverseCode
                .location(code);
       coder.reverseGeoCode(result);
    }

    public void destoryGeoCoder()
    {
        coder.destroy();
    }


    public GeoCoder getGeoCoder()
    {
        return coder;
    }

    public LocationClient getLocationClient() {
        return mLocationClient;
    }

    public MapView getMapView() {
        return mMapView;
    }

    public BaiduMap getMap() {
        return mBaiduMap;
    }


    public void setLocationData(double latitude, double Longitude,Bitmap bit) {
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(0)//不要圈圈
                .direction(0)// 此处设置开发者获取到的方向信息，顺时针0-360
                .latitude(latitude)
                .longitude(Longitude).build();
        // 设置定位数据
        mBaiduMap.setMyLocationData(locData);
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromBitmap(bit);
         MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker);
          mBaiduMap.setMyLocationConfigeration(config);
    }

    public void removeView(View iv)
    {
        mMapView.removeView(iv);
    }

    public Point getCenterPoint()
    {
        return mBaiduMap.getMapStatus().targetScreen;
    }


    public void addView(View ima, Point poi){
        MapViewLayoutParams mlp = new MapViewLayoutParams.Builder().layoutMode(MapViewLayoutParams.ELayoutMode.absoluteMode)
                .point(poi).build();
        mMapView.addView(ima, mlp);
    }


    public MyOverlay addOverlay(Bitmap bit,double latitude, double Longitude, int index){
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromBitmap(bit);

        LatLng code = new LatLng(latitude, Longitude);
        //BitmapDescriptor bitmap = BitmapDescriptorFactory
        //	.fromResource(R.drawable.circle);
        // 构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions().position(code)
                .icon(bitmap).zIndex(index);
         // circle=mBaiduMap.addOverlay(option);
        return new MyOverlay(mBaiduMap.addOverlay(option));
    }

    public void addInfWindow(View ima,double latitude, double Longitude,int len){

            LatLng ll = new LatLng(latitude, Longitude);
            mInfoWindow = new InfoWindow(ima, ll, len);
            mBaiduMap.showInfoWindow(mInfoWindow);
    }

    public void hideInfoWindow()
    {
        if(mBaiduMap!=null&&mInfoWindow!=null)
        {
            mBaiduMap.hideInfoWindow();
            mInfoWindow=null;
        }

    }

    public Boolean infWindowIsNull()
    {
       if(mInfoWindow!=null)
           return false;
        else
           return true;
    }




    public void instancePoiSearch() {
        mPoiSearch=PoiSearch.newInstance();
    }

    public PoiSearch  getPoiSearch ()
    {
        return mPoiSearch ;
    }

    public void instanceSuggestionSearch() {
        mSuggestionSearch = SuggestionSearch.newInstance();
    }

    public SuggestionSearch getSuggestionSearch()
    {
        return mSuggestionSearch;
    }

    public void requestSuggestion(String keyword,String city)
    {
        mSuggestionSearch
                .requestSuggestion((new SuggestionSearchOption())
                        .keyword(keyword).city(city));
    }

    public void destorySuggestionSearch()
    {
        mSuggestionSearch.destroy();
    }

    public void GeoCode(String city,String address) {
        coder.geocode(new GeoCodeOption().city(
                city)
                .address(address));
    }

    public void hiden() {
        mMapView.removeViewAt(1);// 隐藏百度logo
        mMapView.showZoomControls(false);// 不显示缩放控件
        mMapView.showScaleControl(false);// 不显示比例尺控件
    }


    public void zoomOut()
    {
        try {
            float zoomLevel = mMapView.getMap().getMapStatus().zoom + 1;
            MapStatusUpdate u = MapStatusUpdateFactory
                    .zoomTo(zoomLevel);
            mBaiduMap.animateMapStatus(u);
        } catch (NumberFormatException e) {
        }
    }

    public void zoomIn()
    {
        try {
            float zoomLevel = mMapView.getMap().getMapStatus().zoom - 1;
            MapStatusUpdate u = MapStatusUpdateFactory
                    .zoomTo(zoomLevel);
            mBaiduMap.animateMapStatus(u);
        } catch (NumberFormatException e) {
        }
    }

    public LatLng getCenter()
    {
        return new LatLng(mBaiduMap.getMapStatus().target.latitude,mBaiduMap.getMapStatus().target.longitude);
    }


    /*String city="" ;
    String province="" ;

    public void requestCityProvince(double lat,double lng)
    {
        instanceCoder();
        reverseGeoCode(lat, lng);
        coder.setOnGetGeoCodeResultListener(new MyGeoListener());

    }

    public HashMap<String,String> getCityProvice(){
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("city",city);
        hashMap.put("province",province);
        return hashMap;
    }
    *//**
     * 实现实时回调监听
     *//*
    public class MyGeoListener implements OnGetGeoCoderResultListener {
        @Override
        public void onGetGeoCodeResult(GeoCodeResult result) {

        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
          //  int isError = 0;
            if (result == null||result.error != SearchResult.ERRORNO.NO_ERROR)
            //    isError = 2;
           // if (isError == 0)
            {
                return;
            }
            else{
                province = result.getAddressDetail().province;
                city = result.getAddressDetail().city;
            }
        }
    }*/


    }


